package com.yonyou.sto.modules.ims.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yonyou.sto.common.api.CommonResult;
import com.yonyou.sto.domain.InvoiceStatusEnums;
import com.yonyou.sto.modules.ims.dto.ImsInvoiceItemParam;
import com.yonyou.sto.modules.ims.mapper.ImsInvoiceItemMapper;
import com.yonyou.sto.modules.ims.mapper.ImsTaxItemMapper;
import com.yonyou.sto.modules.ims.model.ImsInvoice;
import com.yonyou.sto.modules.ims.model.ImsInvoiceItem;
import com.yonyou.sto.modules.ims.model.ImsTaxItem;
import com.yonyou.sto.modules.ims.service.ImsInvoiceItemService;
import com.yonyou.sto.modules.ims.service.ImsInvoiceService;
import com.yonyou.sto.modules.ums.model.UmsAdmin;
import com.yonyou.sto.modules.ums.model.UmsAdminRoleRelation;
import com.yonyou.sto.modules.ums.service.UmsAdminRoleRelationService;
import com.yonyou.sto.modules.ums.service.UmsAdminService;
import com.yonyou.sto.modules.ums.service.impl.ConfigNameServicImpl;
import io.swagger.annotations.ApiModelProperty;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author aegon
 * @since 2020-09-15
 */
@Service
@Transactional
public class ImsInvoiceItemServiceImpl extends ServiceImpl<ImsInvoiceItemMapper, ImsInvoiceItem> implements ImsInvoiceItemService {

    @Resource
    private ImsInvoiceItemMapper imsInvoiceItemMapper;

    @Resource
    private ImsTaxItemMapper imsTaxItemMapper;

    @Resource
    private ConfigNameServicImpl configNameServic;

    @Resource
    private ImsInvoiceService imsInvoiceService;

    @Resource
    private UmsAdminService adminService;

    @Resource
    private UmsAdminRoleRelationService umsAdminRoleRelationService;

    @Override
    public boolean createBatchInvoiceItem(String billId, List<ImsInvoiceItemParam> imsInvoiceItemParams) {
        try {
            imsInvoiceItemParams.forEach(itemParam -> {
                ImsInvoiceItem item = new ImsInvoiceItem();
                BeanUtils.copyProperties(itemParam, item);
                item.setBillId(billId);
                item.setCreateTime(DateUtil.format(new Date(), DatePattern.NORM_DATE_FORMAT));
                item.setStatus(InvoiceStatusEnums.NOT.getCode());

                imsInvoiceItemMapper.insert(item);
            });
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    @Override
    public List<ImsInvoiceItem> listByBillIds(List<String> collect) {
        List<ImsInvoiceItem> items=baseMapper.listByBillIds(collect);
        items.forEach(es->{
            es.getBillId();




        });
        return items;
    }

    @Override
    public CommonResult replace(ImsInvoiceItem item) {
        // 因为一次只能改一个字段 所以要查出其他所需数据
        ImsInvoiceItem one = getById(item.getId());
        if (one.getProductQuantity() == null) one.setProductQuantity(1.0);

        if (item.getTaxItemId() != null) {
            // 计算价税相关
            ImsTaxItem tax = imsTaxItemMapper.getTaxItemById(item.getTaxItemId());
            if (tax == null) {
                return CommonResult.failed("未查询到相关税目");
            }
            item.setTaxItemName(tax.getTaxItemName());
            item.setTaxRate(tax.getTaxItemRate());
            item.setTaxQuota(tax.getTaxItemRate().multiply(one.getProductAmount()));
            item.setTaxAmount(one.getProductAmount().add(item.getTaxQuota()));

            item.setProductSn(tax.getTaxItemCategoryCode());
        }
        if (item.getProductPrice() != null) {
            item.setProductAmount(item.getProductPrice().multiply(new BigDecimal(one.getProductQuantity())));
        }
        if (item.getProductQuantity() != null) {
            item.setProductAmount(new BigDecimal(item.getProductQuantity()).multiply(one.getProductPrice()));
            item.setTaxAmount(one.getTaxPrice().multiply(BigDecimal.valueOf(item.getProductQuantity())));
        }


        boolean result = updateById(item);
        if (result) return CommonResult.success("更新成功");
        return CommonResult.failed("更新失败");
    }

    @Override
    public boolean updateBatchInvoiceItem(String id, List<ImsInvoiceItemParam> params) {
        QueryWrapper<ImsInvoiceItem> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(ImsInvoiceItem::getBillId, id);
        List<ImsInvoiceItem> list = list(wrapper);

        List<ImsInvoiceItem> items = new ArrayList<>();
        List<ImsInvoiceItemParam> ps = new ArrayList<>();
        params.forEach(param -> {
            // 查询推过来的单据是否存在 存在则更新 不存在则新增
            List<ImsInvoiceItem> collect = list.stream().filter(item -> param.getProductNo().equals(item.getProductNo())).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(collect)) {
                BeanUtils.copyProperties(param, collect.get(0));
                collect.get(0).setStatus(InvoiceStatusEnums.NOT.getCode());
                items.add(collect.get(0));
            }else {
                ps.add(param);
            }
        });
        updateBatchById(items);
        createBatchInvoiceItem(id, ps);
        return true;
    }

    @Override
    public List<ImsInvoiceItem> listByManualIds(List<String> ids) {
        return baseMapper.listByManualIds(ids);
    }

    @Override
    public CommonResult addItem(String manualId, String billSn) {
        ImsInvoiceItem item = new ImsInvoiceItem();
        item.setManualId(manualId);
        item.setBillSn(billSn);
        item.setCreateTime(DateUtil.format(new Date(), DatePattern.NORM_DATE_FORMAT));
        item.setStatus(1);
        int insert = baseMapper.insert(item);
        if (insert > 0) return CommonResult.success(item);
        return CommonResult.failed();
    }

    @Override
    public CommonResult deleteItem(String itemId) {
        int i = baseMapper.deleteById(itemId);
        if (i > 0) return CommonResult.success(true);
        return CommonResult.failed();
    }

    @Override
    public List<ImsInvoiceItem> listByBillId(String billId) {
        return baseMapper.listByBillId(billId);
    }

    @Override
    public boolean updateStatusApply(String id, String name, String code, int billType, double applyje, int Status,int contain) {
        baseMapper.updateStatusApply(Status,id,name, LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),code,billType,applyje,contain);
        return false;
    }

    @Override
    public CommonResult merge(List<String> id) {
        Collections.sort(id);
        List<ImsInvoiceItem> invoiceItems = listByIds(id);
        if (invoiceItems.size()<0){
            return CommonResult.failed("合并失败，没有指定合并数据");
        }
        ImsInvoiceItem imsInvoiceItem = invoiceItems.get(0);
        Double productQuantity = imsInvoiceItem.getProductQuantity();//数量

        if (productQuantity==null){
            return CommonResult.failed("合并失败，数量不存在");
        }
        //BigDecimal productAmount = imsInvoiceItem.getProductAmount();//总价
        BigDecimal taxAmount = imsInvoiceItem.getTaxAmount();//价税合计
        BigDecimal wsje = imsInvoiceItem.getWsje();//无税金额
        try {
            for (int i = 1;i<id.size();i++){
                ImsInvoiceItem imsInvoiceItem1 = invoiceItems.get(i);
                if (imsInvoiceItem1.getProductQuantity()==null){
                    imsInvoiceItem1.setProductQuantity(0.0);
                  //  return CommonResult.failed("合并失败，数量不存在");
                }
                //productAmount=productAmount.add(imsInvoiceItem1.getProductAmount());
                taxAmount=taxAmount.add(imsInvoiceItem1.getTaxAmount());
                wsje=wsje.add(imsInvoiceItem1.getWsje());

//                if (imsInvoiceItem1.getProductQuantity()==0)
//                    return CommonResult.failed("数量为0的不能合并");
                productQuantity=imsInvoiceItem1.getProductQuantity()+productQuantity;
            }

            BigDecimal taxQuota = taxAmount.subtract(wsje);//税额=价税合计-无税金额
            //BigDecimal taxRate = taxQuota.divide(wsje,2,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));//税率=税额/无税金额

           //如果数量不为0重新计算单价
            if(productQuantity!=null &&productQuantity.longValue()!=0){
                BigDecimal taxPrice = taxAmount.divide(new BigDecimal(productQuantity),8,BigDecimal.ROUND_HALF_UP);//含税单价=价税合计/数量
                BigDecimal untaxPrice = wsje.divide(new BigDecimal(productQuantity),8,BigDecimal.ROUND_HALF_UP);//无税单价=无税金额/数量
                imsInvoiceItem.setTaxPrice(taxPrice);
                imsInvoiceItem.setUntaxPrice(untaxPrice);
            }



            imsInvoiceItem.setTaxQuota(taxQuota);
            //imsInvoiceItem.setTaxRate(taxRate);
            imsInvoiceItem.setWsje(wsje);
            imsInvoiceItem.setTaxAmount(taxAmount);
            imsInvoiceItem.setProductQuantity(productQuantity);
            String remove = id.remove(0);
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("数据合并错误:"+e.getMessage());
        }
        removeByIds(id);//
        updateById(imsInvoiceItem);
        return CommonResult.success("合并成功");
    }

    @Override
    public CommonResult create(ImsInvoiceItem invoiceItem) {
        if (StrUtil.isBlank(invoiceItem.getProductName()))return CommonResult.failed("新增失败，请检查物料名称");//物料名称
        if (StrUtil.isBlank(invoiceItem.getCustmatname()))return CommonResult.failed("新增失败，请检查客户物料名称");//客户物料名称
        if (StrUtil.isBlank(invoiceItem.getProductUnit()))return CommonResult.failed("新增失败，请检查单位");//单位
        if (invoiceItem.getProductQuantity()==null&&invoiceItem.getProductQuantity().intValue()<0)return CommonResult.failed("新增失败，请检查数量");//数量
        if (StrUtil.isBlank(invoiceItem.getProductSpec()))return CommonResult.failed("新增失败，请检查规格型号");//型号
        if (StrUtil.isBlank(invoiceItem.getProductSn()))return CommonResult.failed("新增失败，请检查商品税收分类");//商品税收分类
        if (invoiceItem.getTaxPrice()==null&&invoiceItem.getTaxPrice().doubleValue()<0)return CommonResult.failed("新增失败，请检查含税单价");//含税单价
        if (invoiceItem.getUntaxPrice()==null&&invoiceItem.getTaxPrice().doubleValue()<0)return CommonResult.failed("新增失败，请检查无税单价数据");//无税单价
        if (invoiceItem.getTaxRate()==null&&invoiceItem.getTaxPrice().doubleValue()<0)return CommonResult.failed("新增失败，请检查税率");//税率
        if (invoiceItem.getTaxQuota()==null&&invoiceItem.getTaxQuota().doubleValue()<0)return CommonResult.failed("新增失败，请检查税额");//税额
        if (invoiceItem.getTaxAmount()==null&&invoiceItem.getTaxPrice().doubleValue()<0)return CommonResult.failed("新增失败，请检查价税合计");//价税合计
        if (invoiceItem.getWsje()==null&&invoiceItem.getWsje().doubleValue()<0)return CommonResult.failed("新增失败，请检查无税金额");//无税金额
        ImsInvoice imsInvoice = imsInvoiceService.getById(invoiceItem.getBillId());
        invoiceItem.setStatus(imsInvoice.getStatus());//单据状态
        invoiceItem.setManualId(imsInvoice.getId());//主子表关联关系
        invoiceItem.setDjlx(imsInvoice.getDjlx());//单据类型
        invoiceItem.setBillSn(imsInvoice.getBillSn());//单据编码
        invoiceItem.setBillSerial(imsInvoice.getBillSerial());//流水号
        invoiceItem.setCreateTime(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        invoiceItem.setDef1(DateUtil.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        invoiceItem.setId(IdUtil.simpleUUID());

        /*String contain = imsInvoice.getDef1();
        if ("1".equals(contain)){//开票金额含税
            invoiceItem.setApplyje(invoiceItem.getTaxAmount());
            imsInvoice.setApplyje(imsInvoice.getApplyje().add(invoiceItem.getTaxAmount()));
        }else if ("0".equals(contain)){
            invoiceItem.setApplyje(invoiceItem.getWsje());
            imsInvoice.setApplyje(imsInvoice.getApplyje().add(invoiceItem.getWsje()));
        }else {
            return CommonResult.failed("请重新申请开票");
        }*/
        imsInvoice.setPayAmount(imsInvoice.getPayAmount().add(invoiceItem.getTaxAmount()));
        imsInvoice.setWsje(imsInvoice.getWsje().add(invoiceItem.getWsje()));
        imsInvoiceService.save(imsInvoice);
        save(invoiceItem);
        return CommonResult.success("新增成功");
    }

    @Override
    public CommonResult delete(List<String> ids) {
        List<ImsInvoiceItem> invoiceItems = listByIds(ids);
        if (invoiceItems.size()<0)return CommonResult.failed("找不到对应单据");
        List<ImsInvoiceItem> unDelete = invoiceItems.stream().filter(i ->
                i.getStatus() != InvoiceStatusEnums.NOT.getCode()
        ).collect(Collectors.toList());
        if (unDelete.size()>0)return CommonResult.failed("存在非未开票状态的单据，不能删除");
        ImsInvoice imsInvoice = imsInvoiceService.getOne(new LambdaQueryWrapper<ImsInvoice>()
                .eq(ImsInvoice::getId, invoiceItems.get(0).getManualId())
        );
        List<ImsInvoiceItem> list = list(new LambdaQueryWrapper<ImsInvoiceItem>()
                .eq(ImsInvoiceItem::getManualId, imsInvoice.getId())
                .eq(ImsInvoiceItem::getStatus,imsInvoice.getStatus())
        );
        List<String> itemIds = list.stream().map(i -> i.getId()).collect(Collectors.toList());
        for (String id:ids) {
            itemIds.remove(id);
        }
        String contain = imsInvoice.getDef1();//开票金额是否含税
        BigDecimal jshj = new BigDecimal(0).setScale(2,BigDecimal.ROUND_HALF_UP);
        BigDecimal wsje = new BigDecimal(0).setScale(2,BigDecimal.ROUND_HALF_UP);
        BigDecimal tax = new BigDecimal(0).setScale(2,BigDecimal.ROUND_HALF_UP);

        if(itemIds.size()==0){
            imsInvoice.setPayAmount(jshj);
            imsInvoice.setWsje(wsje);
            tax = jshj.subtract(wsje);
            imsInvoice.setTaxAmount(tax);
            imsInvoiceService.update(new LambdaUpdateWrapper<ImsInvoice>().eq(ImsInvoice::getId,imsInvoice.getId())
                    .set(ImsInvoice::getPayAmount,imsInvoice.getPayAmount()).set(ImsInvoice::getWsje,imsInvoice.getWsje())
                    .set(ImsInvoice::getTaxAmount,imsInvoice.getTaxAmount())
            );
            removeByIds(ids);
            return CommonResult.success("删除成功");
        }
        List<ImsInvoiceItem> list1 = list(new LambdaQueryWrapper<ImsInvoiceItem>()
                .in(ImsInvoiceItem::getId, itemIds)
                .eq(ImsInvoiceItem::getStatus,imsInvoice.getStatus())
        );
        for (ImsInvoiceItem invoiceItem:list1) {
            jshj=jshj.add(invoiceItem.getTaxAmount());
            wsje=wsje.add(invoiceItem.getWsje());
        }
        tax = jshj.subtract(wsje);
        imsInvoice.setTaxAmount(tax);
        /*if(imsInvoice.getStatus()!=1){
            if ("1".equals(contain)||"2".equals(contain)){//开票金额含税
                //invoiceItem.setApplyje(invoiceItem.getTaxAmount());
                imsInvoice.setApplyje(jshj);
            }else if ("0".equals(contain)||"3".equals(contain)){
                //invoiceItem.setApplyje(invoiceItem.getWsje());
                imsInvoice.setApplyje(wsje);
            }else {
                return CommonResult.failed("请重新申请开票");
            }
        }*/
        imsInvoice.setPayAmount(jshj);
        imsInvoice.setWsje(wsje);
        imsInvoiceService.update(new LambdaUpdateWrapper<ImsInvoice>().eq(ImsInvoice::getId,imsInvoice.getId())
                .set(ImsInvoice::getPayAmount,imsInvoice.getPayAmount()).set(ImsInvoice::getWsje,imsInvoice.getWsje()));
        removeByIds(ids);
        return CommonResult.success("删除成功");
    }

    @Override
    public CommonResult deleteApply(String username,List<String> ids) {
        UmsAdmin umsAdmin = adminService.getAdminByUsername(username);
        Boolean isKF = false;
        if(umsAdmin!=null){
            List<UmsAdminRoleRelation> list = umsAdminRoleRelationService.list(new LambdaQueryWrapper<UmsAdminRoleRelation>().eq(UmsAdminRoleRelation::getAdminId, umsAdmin.getId()));
            if(list!=null&&list.size()>0){
                for (UmsAdminRoleRelation umsAdminRoleRelation: list) {
                    if ("10".equals(umsAdminRoleRelation.getRoleId())){
                        isKF = true;
                    }
                }
            }

        }
        if (isKF){
            return CommonResult.failed("客服用户无数据操作权限");
        }
        List<ImsInvoiceItem> invoiceItems = listByIds(ids);
        if (invoiceItems.size()<0)return CommonResult.failed("找不到对应单据");
        List<ImsInvoiceItem> unDelete = invoiceItems.stream().filter(i ->
                i.getStatus() != InvoiceStatusEnums.APPLY.getCode()
        ).collect(Collectors.toList());
        if (unDelete.size()>0)return CommonResult.failed("存在非待开票状态的单据，不能删除");
        removeByIds(ids);
        return CommonResult.success("删除成功");
    }
}
